package XishiBackend.services.microsite;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import XishiBackend.base.Constant;
import XishiBackend.models.entity.Distribution;
import XishiBackend.models.entity.User;
import XishiBackend.models.entity.Voucher;
import XishiBackend.models.repository.DistributionRepository;
import XishiBackend.models.repository.UserRepository;
import XishiBackend.models.repository.VoucherRepository;

@Service
@Transactional
public class MicrositeUserService {
    @Autowired
    private UserRepository uR;
    @Autowired
    private DistributionRepository dR;
    @Autowired
    private VoucherRepository vR;
    
    public User findUserByOpenId(String openId) {
        User u = uR.findByOpenId(openId);
        if(u == null) {
            u = new User(openId,Constant.NOT_BLACK,"",0);
            u = uR.save(u);
        }
        return u;
    }
    
    public List<Map<String,Object>> findAllDistribution() {
        Iterator<Distribution> iter = dR.findAll().iterator();
        List<Map<String, Object>> dList = new ArrayList<Map<String, Object>>();
        while(iter.hasNext()) {
            Distribution d = iter.next();
            if(d.isEnable()) {
                Map<String, Object> m = new HashMap<String,Object>();
                m.put("id",d.getId());
                m.put("name", d.getName());
                m.put("tel", d.getTel());
                m.put("address", d.getAddress());
                m.put("map", d.getMap());
                dList.add(m);
            }
        }
        return dList;
    }
    
    public User findUserById(long userId) {
        return uR.findOne(userId);
    }
    
    public Distribution findDistributionById(long distributionId) {
        return dR.findOne(distributionId);
    }
    
    public boolean save(User u) {
        User ru = uR.save(u);
        if(ru.getDistributionId() != u.getDistributionId()) {
            return false;
        }
        if(!ru.getValidateCode().equals(u.getValidateCode())) {
            return false;
        }
        if(!ru.getTel().equals(u.getTel())) {
            return false;
        }
        return true;
    }
    
    public List<Voucher> findVoucherByUserId(long userId) {
        return vR.findByUserId(userId);
    }
}
